class CompaniesController < ApplicationController
  # GET /companies
  # GET /companies.xml
  
  before_filter :login_required
  
  def index
	  @title = "Index Companies"
    @companies = Company.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @companies }
    end
  end

  # GET /companies/1
  # GET /companies/1.xml
  def show
    @title = "Show Company"
    @company = Company.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @company }
    end
  end

  # GET /companies/new
  # GET /companies/new.xml
  def new
    @title = "New Company"
    @company = Company.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @company }
    end
  end

  # GET /companies/1/edit
  def edit
    @title = "Edit Company"
    @company = Company.find(params[:id])
  end

  # POST /companies
  # POST /companies.xml
  def create
    @title = "Create Company"
    @company = Company.new(params[:company])
    if request.xhr?
        if @company.save
          @companies = Company.all
          @computers = []
          for computer in Computer.all
            if (computer.room_id == nil) 
              @computers << computer
            end
          end
          render :update do |page|
            page.replace_html 'tabs-1', :partial => 'supervisions/tree', :locals => {:companies => @companies, :computers => @computers}
          end
        else
          render :nothing => true
        end
      else    
        respond_to do |format|
          if @company.save
            flash[:notice] = 'Company was successfully created.'
            format.html { redirect_to(@company) }
            format.xml  { render :xml => @company, :status => :created, :location => @company }
          else
            format.html { render :action => "new" }
            format.xml  { render :xml => @company.errors, :status => :unprocessable_entity }
          end
        end
      end
  end

  # PUT /companies/1
  # PUT /companies/1.xml
  def update
    @title = "Update Company"
    @company = Company.find(params[:id])

    respond_to do |format|
      if @company.update_attributes(params[:company])
        flash[:notice] = 'Company was successfully updated.'
        format.html { redirect_to(@company) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @company.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /companies/1
  # DELETE /companies/1.xml
  def destroy
    @title = "Destroy Company"
    @company = Company.find(params[:id])
    @company.destroy

    respond_to do |format|
      format.html { redirect_to(companies_url) }
      format.xml  { head :ok }
    end
  end
end
